angular.module('panels')
    .directive("panelBamChannelServiceAvailability", function ($http, loadConf, $timeout, $log, moment, tabService) {
        return {
            scope: {},
            link: function (scope) {
                function gradientColor(color) {
                    return {
                        radialGradient: {cx: 0.5, cy: 0.3, r: 0.7},
                        stops: [
                            [0, color],
                            [1, Highcharts.Color(color).brighten(-0.1).get('rgb')] // darken
                        ]
                    };
                }

                function getHighChartOptions(store, categories) {
                    return {
                        chart: {
                            type: 'bar'
                        },
                        title: {
                            text: ''
                        },
                        xAxis: {
                            categories: categories
                        },
                        yAxis: {
                            min: 0,
                            title: {
                                text: '业务量',
                                enabled: false
                            }
                        },
                        legend: {
                            reversed: true
                        },
                        plotOptions: {
                            series: {
                                stacking: 'normal'
                            }
                        },
                        series: [{
                            name: '不可用',
                            color: gradientColor('#DD4444'),
                            data: store[0]
                        }, {
                            name: '可用',
                            color: gradientColor('#00CC00'),
                            data: store[1]
                        }]
                    };
                }

                scope.options = getHighChartOptions({0: [], 1: []}, []);
                scope.panelTitle = '各渠道业务可用性';
                loadConf('panel-bam-channel-service-availability.yml').then(function (setting) {
                    scope.more = setting.more;
                    var preData, timeoutId;
                    scope.$on('$destroy', function () {
                        timeoutId && $timeout.cancel(timeoutId);
                    });
                    (function updateData() {
                        $http.jsonp(setting.countQueryUrl, {params: {date: moment().format('YYYY-MM-DD')}}).success(function (data) {
                            if (angular.equals(data, preData)) {
                                return false;
                            } else {
                                preData = data;
                                data = angular.copy(data);
                            }

                            var categories = [], store = {0: [], 1: []};
                            for (var i = 0; i < data.length; i++) {
                                var channel = data[i];
                                categories.push(channel["KBP_CAPTION"]);
                                angular.forEach(store, function (seriesData, type) {
                                    var count = parseInt(channel.COUNT[type]) || 0,
                                        kbpCaption = channel["KBP_CAPTION"],
                                        kbpClass = channel["KBP_CLASS"];
                                    seriesData.push({
                                        y: count,
                                        events: {
                                            click: function () {
                                                if (setting.viewDetailUrl) {
                                                    var viewDetailUrl = setting.viewDetailUrl.replace(/\{KBP_CLASS}/g, kbpClass);
                                                    scope.$apply(function () {
                                                        tabService.addTab({
                                                            name: '(' + kbpCaption + ')渠道业务可用性',
                                                            url: viewDetailUrl
                                                        });
                                                    });
                                                }
                                            }
                                        }
                                    });
                                });
                                // 限制展示的列数
                                if (categories.length == (setting.maxColumnsAllowed || 5)) break;
                            }

                            // 通知更新charts
                            scope.options = getHighChartOptions(store, categories);
                        }).then(callback, callback);
                        function callback() {
                            if (setting.updateInterval > 0) {
                                timeoutId = $timeout(updateData, setting.updateInterval * 1000);
                            }
                        }

                        $log.debug('panel update data: bam-channel-service-availability');
                    }());
                });
            },
            templateUrl: 'app/panel/highcharts-default.html'
        };
    });